package com.zxd.interview.eightthread.stop;

/**
 * sleep 过程当中interrupt
 */
public class RightWayStopThreadWithSleep implements Runnable {

    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(new RightWayStopThreadWithSleep());
        thread.start();
        thread.sleep(500);
        // 线程不响应停止
        thread.interrupt();
    }

    @Override
    public void run() {
        try {
            int num = 0;
            // !Thread.currentThread().isInterrupted() 这一段不是判断的关键
            while (!Thread.currentThread().isInterrupted() && num <= Integer.MAX_VALUE / 2) {
                if (num % 100 == 0) {
                    System.out.println("num =>" + num);
                    Thread.sleep(100);
                }
                num++;
            }
            System.out.println("执行完成");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }/**
     Sleep 可以正确检测到中断异常并且要求程序处理
    Connected to the target VM, address: '127.0.0.1:12340', transport: 'socket'
num =>0
num =>100
num =>200
num =>300
num =>400
num =>500
num =>600
num =>700
num =>800
num =>900
java.lang.InterruptedException: sleep interrupted
	at java.lang.Thread.sleep(Native Method)
	at com.zxd.interview.eightthread.stop.RightWayStopThreadWithSleep.run(RightWayStopThreadWithSleep.java:24)
	at java.lang.Thread.run(Thread.java:750)
    */


}
